<template>
  <view class="ppt-list-container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <u-search
        v-model="searchKeyword"
        placeholder="搜索演示文稿"
        :showAction="false"
        @search="handleSearch"
        @clear="handleClearSearch">
      </u-search>
    </view>

    <!-- 筛选标签 -->
    <view class="filter-tags">
      <u-tag
        v-for="tag in filterTags"
        :key="tag.value"
        :text="tag.label"
        :type="activeFilter === tag.value ? 'primary' : 'info'"
        @click="handleFilter(tag.value)">
      </u-tag>
    </view>

    <!-- PPT列表 -->
    <scroll-view
      scroll-y
      class="ppt-list-scroll"
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="refreshList">
      <view class="ppt-list">
        <!-- 新建卡片 -->
        <view class="ppt-card create-card" @click="createNewPPT">
          <u-icon name="plus" size="40" color="#999"></u-icon>
          <text class="create-text">新建演示文稿</text>
        </view>

        <!-- PPT卡片 -->
        <view
          v-for="ppt in pptList"
          :key="ppt.id"
          class="ppt-card"
          @click="editPPT(ppt.id)"
          @longpress="showActionMenu(ppt)">
          <image :src="ppt.cover" mode="aspectFill" class="ppt-cover"></image>
          <view class="ppt-info">
            <text class="ppt-title">{{ ppt.title }}</text>
            <text class="ppt-date">{{ formatDate(ppt.updatedAt) }}</text>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <u-loadmore
        :status="loadStatus"
        :icon-type="loadStatus === 'loading' ? 'circle' : 'none'"
        :load-text="loadText">
      </u-loadmore>
    </scroll-view>

    <!-- 操作菜单 -->
    <u-action-sheet
      :list="actionList"
      v-model="showAction"
      :cancel-btn="true"
      @click="handleAction">
    </u-action-sheet>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { usePPTStore } from '@/stores/ppt'
import dayjs from 'dayjs'

const pptStore = usePPTStore()

// 数据状态
const searchKeyword = ref('')
const activeFilter = ref('all')
const pptList = ref([])
const refreshing = ref(false)
const loadStatus = ref('loadmore')
const showAction = ref(false)
const currentPPT = ref(null)

// 筛选标签
const filterTags = [
  { label: '全部', value: 'all' },
  { label: '最近', value: 'recent' },
  { label: '收藏', value: 'favorite' }
]

// 加载文本
const loadText = {
  loadmore: '上拉加载更多',
  loading: '正在加载...',
  nomore: '没有更多了'
}

// 操作菜单
const actionList = [
  {
    text: '重命名',
    color: '#606266',
    fontSize: '28rpx'
  },
  {
    text: '删除',
    color: '#fa3534',
    fontSize: '28rpx'
  },
  {
    text: '复制',
    color: '#606266',
    fontSize: '28rpx'
  }
]

// 生命周期
onMounted(() => {
  loadPPTList()
})

// 加载PPT列表
async function loadPPTList() {
  try {
    loadStatus.value = 'loading'
    const list = await pptStore.loadPPTList()
    pptList.value = list
    loadStatus.value = list.length < 10 ? 'nomore' : 'loadmore'
  } catch (error) {
    console.error('加载PPT列表失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    refreshing.value = false
  }
}

// 刷新列表
async function refreshList() {
  refreshing.value = true
  await loadPPTList()
}

// 加载更多
async function loadMore() {
  if (loadStatus.value !== 'loadmore') return
  
  // 模拟分页加载
  loadStatus.value = 'loading'
  setTimeout(() => {
    // 这里应该调用带分页参数的API
    loadStatus.value = 'nomore'
  }, 1000)
}

// 搜索处理
function handleSearch() {
  // 实现搜索逻辑
  console.log('搜索关键词:', searchKeyword.value)
}

function handleClearSearch() {
  searchKeyword.value = ''
  // 重置搜索状态
}

// 筛选处理
function handleFilter(filter) {
  activeFilter.value = filter
  // 根据筛选条件重新加载列表
}

// 新建PPT
function createNewPPT() {
  pptStore.initNewPPT()
  uni.navigateTo({
    url: '/pages/editor/editor'
  })
}

// 编辑PPT
function editPPT(id) {
  uni.navigateTo({
    url: `/pages/editor/editor?id=${id}`
  })
}

// 显示操作菜单
function showActionMenu(ppt) {
  currentPPT.value = ppt
  showAction.value = true
}

// 处理操作
function handleAction(index) {
  if (!currentPPT.value) return
  
  switch (index) {
    case 0: // 重命名
      renamePPT(currentPPT.value)
      break
    case 1: // 删除
      deletePPT(currentPPT.value.id)
      break
    case 2: // 复制
      duplicatePPT(currentPPT.value)
      break
  }
}

// 重命名PPT
function renamePPT(ppt) {
  uni.showModal({
    title: '重命名',
    content: '请输入新的演示文稿名称',
    editable: true,
    placeholderText: ppt.title,
    success: async (res) => {
      if (res.confirm && res.content) {
        try {
          await pptStore.savePPT({
            ...ppt,
            title: res.content
          })
          await loadPPTList()
          uni.showToast({
            title: '重命名成功',
            icon: 'success'
          })
        } catch (error) {
          uni.showToast({
            title: '重命名失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 删除PPT
function deletePPT(id) {
  uni.showModal({
    title: '提示',
    content: '确定要删除这个演示文稿吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await pptStore.deletePPT(id)
          await loadPPTList()
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          })
        } catch (error) {
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 复制PPT
function duplicatePPT(ppt) {
  uni.showLoading({
    title: '复制中...'
  })
  
  try {
    // 模拟复制操作
    setTimeout(() => {
      uni.hideLoading()
      uni.showToast({
        title: '复制成功',
        icon: 'success'
      })
      loadPPTList()
    }, 1000)
  } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: '复制失败',
      icon: 'none'
    })
  }
}

// 格式化日期
function formatDate(date) {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}
</script>

<style lang="scss" scoped>
.ppt-list-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8f8f8;
}

.search-bar {
  padding: 20rpx;
  background-color: #fff;
}

.filter-tags {
  padding: 20rpx;
  display: flex;
  background-color: #fff;
  
  .u-tag {
    margin-right: 20rpx;
  }
}

.ppt-list-scroll {
  flex: 1;
  overflow: hidden;
}

.ppt-list {
  padding: 20rpx;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.ppt-card {
  height: 300rpx;
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  position: relative;
  
  &.create-card {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border: 2rpx dashed #e0e0e0;
    
    .create-text {
      margin-top: 20rpx;
      font-size: 28rpx;
      color: #999;
    }
  }
}

.ppt-cover {
  width: 100%;
  height: 200rpx;
}

.ppt-info {
  padding: 20rpx;
  
  .ppt-title {
    font-size: 28rpx;
    color: #333;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
  
  .ppt-date {
    margin-top: 10rpx;
    font-size: 24rpx;
    color: #999;
    display: block;
  }
}
</style>